﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using ST.Buz.Base.Enums;
using ST.Common.Util.Security;
using Microsoft.Data.SqlClient;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using ST.Buz.Base.ViewModel;

namespace ST.Buz.Service
{
	public partial interface IServiceSysAttachment
	{
		/// <summary>
		/// 获取分页列表
		/// </summary>
		/// <param name="pageNum">页面索引（以1开始）</param>
		/// <param name="pageSize">每页显示条数</param>
		/// <param name="dts">起始时间（不过滤时传DateTime.MinValue）</param>
		/// <param name="dte">截止时间（不过滤时传DateTime.MinValue）</param>
		/// <returns></returns>
		PageData GetPageList(VMS_Sys_Attachment searchModel);

		/// <summary>
		/// 获取总数
		/// </summary>
		/// <param name="infoID"></param>
		/// <param name="tblName"></param>
		/// <param name="dts"></param>
		/// <param name="dte"></param>
		/// <returns></returns>
		int GetCount(VMS_Sys_Attachment searchModel);

		List<Sys_Attachment> GetFiles(int tableID, int infoID);

		/// <summary>
		/// 删除信息
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		bool Delete(int id, UserSession sessionCurrent, bool deleteFile = false);
	}

	public partial class ServiceSysAttachment
	{
		private readonly IWebHostEnvironment hostingEnvironment;
		private readonly IServiceSysLog serviceSysLog;

		public ServiceSysAttachment(BuzContext ctx,
			IWebHostEnvironment _hostingEnvironment,
			IServiceSysLog _serviceSysLog,
			ILogger<ServiceSysAttachment> log)
		{
			hostingEnvironment = _hostingEnvironment;
			serviceSysLog = _serviceSysLog;
			context = ctx;
			logger = log;
		}

		private IQueryable<Sys_Attachment> GetQuery(VMS_Sys_Attachment searchModel)
		{
			var query = from m in context.SysAttachment where m.TableID == searchModel.tblid && m.InfoID == searchModel.infoid select m;
			if (searchModel.date_s != DateTime.MinValue)
			{
				query = query.Where(m => m.AddDate >= searchModel.date_s);
			}
			if (searchModel.date_e != DateTime.MinValue)
			{
				query = query.Where(m => m.AddDate <= searchModel.date_e);
			}
			return query;
		}

		/// <summary>
		/// 分页列表
		/// </summary>
		public PageData GetPageList(VMS_Sys_Attachment searchModel)
		{
			PageData result = null;
			try
			{
				searchModel.Validate();
				var query = GetQuery(searchModel);
				switch (searchModel.sortby)
				{
					default:
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.ID) : query.OrderByDescending(e => e.ID);
						break;
				}
				result = new PageData(searchModel.pnum.Value, searchModel.psize.Value);
				result.Load(query);
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取分页数据出错");
				throw new BuzException("获取分页数据失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return result;
		}

		public List<Sys_Attachment> GetFiles(int tableID, int infoID)
		{
			try
			{
				var query = from q in context.SysAttachment
							where q.TableID == tableID && q.InfoID == infoID
							select q;
				return query.ToList();
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取分页数据出错");
				throw new BuzException("获取分页数据失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		public int GetCount(VMS_Sys_Attachment searchModel)
		{
			var query = GetQuery(searchModel);
			return query.Count();
		}

		/// <summary>
		/// 删除信息
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public bool Delete(int id, UserSession sessionCurrent, bool deleteFile = false)
		{
			bool success = false;
			try
			{
				//if (logger.IsEnabled(LogLevel.Debug))
				//{
				//	logger.LogDebug($"参数->id:{id}，state:{state}，remark:{remark}");
				//}
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}

				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						DateTime dtNow = DateTime.Now;
						string ip = GetRequestIP();

						var modelOld = Get(id);
						Delete(modelOld);

						if (deleteFile && !string.IsNullOrEmpty(modelOld.FileUrl))
						{
							string filePath = Path.Combine(hostingEnvironment.WebRootPath, modelOld.FileUrl.TrimStart('/'));
							if (File.Exists(filePath))
							{
								File.Delete(filePath);
							}
						}

						serviceSysLog.Add(sessionCurrent, ip, $"删除附件，原信息：", modelOld, dtNow);
						#endregion

						trans.Commit();
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}

				success = true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "删除出错");
				throw new BuzException("删除失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return success;
		}
	}
}